package com.hxzy.shop.cachedao;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.hxzy.shop.constant.RedisConstant;
import com.hxzy.shop.entity.Member;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * AuthCatche的redis操作
 */
@Service
public class AuthCacheServiceImpl implements AuthCacheService {

    /**
     * Redis - 验证码
     */
    private static final String VERIFICATION_CODE = "verification:code:";
    /**
     * 小程序请求用户信息
     */
    private static final String APPLET_USER_INFO= RedisConstant.APPLET_USER_INFO;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public void saveToken(String k, String v, int expired) {
        Boolean bool = redisTemplate.hasKey(k);
        if (bool) {
            redisTemplate.delete(k);
        }
        redisTemplate.opsForValue().set(k, v, expired, TimeUnit.SECONDS);
    }



    @Override
    public void emptyToken(String k) {
        Boolean bool = redisTemplate.hasKey(k);
        if (bool) {
            redisTemplate.delete(k);
        }
    }

    @Override
    public void saveVCode(String k, String v) {
        Boolean bool = redisTemplate.hasKey(VERIFICATION_CODE+k);
        if (bool) {
            redisTemplate.delete(VERIFICATION_CODE+k);
        }
        redisTemplate.opsForValue().setIfAbsent(VERIFICATION_CODE+k, v, 10, TimeUnit.MINUTES);
    }

    @Override
    public void emptyVCode(String k) {
        Boolean bool = redisTemplate.hasKey(VERIFICATION_CODE+k);
        if (bool) {
            redisTemplate.delete(VERIFICATION_CODE+k);
        }
    }

    @Override
    public String getVCode(String k) {
        String str = null;
        Boolean bool = redisTemplate.hasKey(VERIFICATION_CODE+k);
        if (bool) {
            str = redisTemplate.opsForValue().get(VERIFICATION_CODE+k);
        }
        return str;
    }

    @Override
    public void saveAppletUSerInfo(String token, Member member) {
        if (ObjectUtil.isEmpty(token)||ObjectUtil.isEmpty(member)){
            return;
        }
        String memberStr = JSONUtil.toJsonStr(member);
        redisTemplate.opsForValue().set(APPLET_USER_INFO+token,memberStr,7,TimeUnit.DAYS);
    }
}
